<template>
  <div class="flex flex-col h-full">
    <vxe-card
      v-if="route.query.version"
      title=""
      class="w-full"
      :border="false"
    >
      <div class="flex items-center">
        <div class="border-arrow" @click="toPrevPage">
          <FontIcon icon="icon-left" />
        </div>
        <div class="text-[#242930] ml-4">
          {{ t("formula_detail.specification_list1") }}
        </div>
      </div>
    </vxe-card>

    <vxe-card
      title=""
      :class="['w-full', route.query.version ? 'mt-[16px]' : '']"
      :border="false"
    >
      <AuForm ref="formRef" :formList="formList" @submit="search" />
    </vxe-card>

    <div class="mt-[16px] flex-grow overflow-hidden">
      <AuTable ref="tableRef" v-bind="gridOption" @actionClick="actionClick" />
    </div>
    <vxe-card
      v-if="route.query.version"
      title=""
      class="w-full mt-[16px]"
      :border="false"
    >
      <el-button
        type="primary"
        style="float: right"
        @click="saveFormulaSpecification"
      >
        {{ t("buttons.confirm") }}
      </el-button>
    </vxe-card>

    <AuModal
      v-model="showPopup"
      :title="
        activeType == ACTION_TYPE.TADD
          ? t('formula_detail.add_specification')
          : t('formula_detail.edit_specification')
      "
      :width="780"
      show-zoom
      :padding="false"
      @handleConfirm="handleConfirm"
    >
      <div class="flex justify-center py-[30px]" style="overflow-x: hidden">
        <!-- <AuForm
          ref="formPopRef"
          :formList="formPopList"
          :isInline="false"
          :hiddenBtn="true"
          labelWidth="100px"
          class="!w-[300px]"
        /> -->
        <el-form
          ref="formSpecRef"
          style="width: 100%"
          :model="dynamicValidateForm"
          label-position="left"
          label-width="auto"
          :rules="rules"
          flow
        >
          <el-form-item
            prop="name"
            :label="t('formula_detail.specification_name')"
            label-width="127px"
            class="formStyle"
          >
            <el-input
              v-model="dynamicValidateForm.name"
              style="width: 198px"
              :maxlength="30"
              :placeholder="t('formula_detail.specification_name_placeholder')"
            />
          </el-form-item>
          <!--  <span style="margin-right: 4px; color: red">*</span
          ><label class="el-form-item__label">规格属性</label> -->
          <div style="width: 100%; background: #f0f6ff">
            <div class="flex items-center justify-between px-[20px] h-[40px]">
              <div>
                <label
                  class="el-form-item__label !text-[--autata-font-color]"
                  >{{ t("formula_detail.specification_attr") }}</label
                >
              </div>
              <el-link
                :underline="false"
                type="primary"
                style="margin-top: -8px"
                @click="addDomain"
              >
                <iconify-icon-online icon="ep:plus" />&nbsp;{{ t("table.add") }}
              </el-link>
            </div>
            <el-scrollbar max-height="400px">
              <el-form-item
                v-for="(domain, index) in dynamicValidateForm.domains"
                :key="domain.key"
                label=""
                :prop="'domains.' + index + '.value'"
                class="formStyle"
              >
                <div
                  class="w-full pr-[20px] !text-[--autata-font-gray2-color] flex"
                >
                  <div class="input-with-label items-center w-[44%]">
                    <div class="w-[176px]">
                      <span style="margin-right: 2px; color: red">*</span>
                      {{ t("formula_detail.specification_attr_name") }}
                    </div>
                    <el-input
                      v-model="domain.autata_value"
                      style="padding-left: 15px"
                      class="flex-grow"
                      :maxlength="20"
                      :placeholder="
                        t('formula_detail.specification_attr_name_placeholder')
                      "
                    />
                  </div>
                  <div class="input-with-label w-[44%] ml-[2%]">
                    <div class="w-[148px]">
                      {{ t("formula_detail.specification_external_id") }}
                    </div>
                    <el-input
                      v-model="domain.third_value"
                      :maxlength="20"
                      :placeholder="
                        t(
                          'formula_detail.specification_external_id_placeholder'
                        )
                      "
                    />
                  </div>

                  <el-link
                    :underline="false"
                    class="!text-[#EA2626] !text-[12px] w-[50px] ml-auto"
                    @click.prevent="removeDomain(domain)"
                  >
                    <FontIcon style="font-size: 14px" icon="icon-delete" />
                    <span class="inline-block align-middle"
                      >&nbsp;{{ t("buttons.delete") }}</span
                    >
                  </el-link>
                  <!--                  <el-col :span="3" class="text-right">-->
                  <!--                  </el-col>-->
                </div>
              </el-form-item>
            </el-scrollbar>
          </div>
          <!-- <el-form-item>
           <el-button @click="addDomain">新增规格属性</el-button>
            <el-link :underline="false" type="primary" @click="addDomain">
              <iconify-icon-online icon="ep:plus" />&nbsp;新增
            </el-link>
          </el-form-item> -->
        </el-form>
      </div>
    </AuModal>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, nextTick, onMounted, reactive, ref } from "vue";
import { AuForm } from "@/components/AuForm";
import { AuTable } from "@/components/AuTable";
import { AuModal } from "@/components/AuModal";
import { ACTION_TYPE, PropDefines } from "@/components/AuTable/type";

import {
  SpecificationProp,
  getSpecificationList,
  specificationAdd,
  specificationUpdate,
  SpecificationSubProp,
  specificationDelete
} from "@/api/cabinet/specification";

import { getMaterialListForFormula } from "@/api/cabinet/material";

import { ElMessage, FormInstance, FormRules, FormProps } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { isString, useGlobal } from "@pureadmin/utils";

import { VxeUI } from "vxe-table";
import { useI18n } from "vue-i18n";

defineOptions({
  name: "CabinetSpecification"
});

const { t } = useI18n();

//规格维护页面字段
const labelPosition = ref<FormProps["labelPosition"]>("right");
const formSpecRef = ref<FormInstance>();
let dynamicValidateForm = reactive<{
  domains: Partial<SpecificationSubProp>[];
  name: string;
  id: number;
}>({
  domains: [
    {
      key: 1,
      autata_value: "",
      third_value: ""
    }
  ],
  name: "",
  id: null
});

interface DomainItem {
  key: number;
  autata_value: string;
  third_value: string;
}

const showPopup = ref(false); //新增、修改维护弹框
const formPopRef = ref(); //维护对象
const activeType = ref<ACTION_TYPE>(null);

// 基础表单数据
interface FormData {
  id: string | number;
  name: string;
  attr: string;
  third_detail: string;
}

const formSpecData = reactive<FormData>({
  id: "",
  name: "",
  attr: "",
  third_detail: ""
});

const dateValue = ref("");
const size = ref<"default" | "large" | "small">("default");

const { proxy } = getCurrentInstance();

// region 页面及组件变量集合
const { $storage } = useGlobal<GlobalPropertiesApi>();
const router = useRouter();
const route = useRoute();

const showUploadModal = ref(false);

const rules: FormRules = {
  name: {
    required: true,
    message: t("formula_detail.specification_name_required"),
    trigger: "blur"
  }
};

const formList = ref([
  {
    type: "input",
    key: "id",
    label: "formula_detail.specification_id",
    placeholder: "formula_detail.specification_id_placeholder"
  },
  {
    type: "input",
    key: "name",
    label: "formula_detail.specification_name",
    placeholder: "formula_detail.specification_name_placeholder"
  }
]);

const showDetailModal = ref(false);
const gridOption = reactive<PropDefines>({
  isServerPage: false,
  showCheckbox: true,
  columns: [
    { field: "id", title: "formula_detail.specification_id", width: 90 },
    { field: "name", title: "formula_detail.specification_name", width: 140 },
    {
      field: "attr",
      title: "formula_detail.specification_attr",
      formatter: ({ cellValue }) => {
        return cellValue.replaceAll(",", "｜");
      }
    },
    {
      field: "create_time",
      title: "formula_detail.create_time"
    }
  ],
  actions: [ACTION_TYPE.TADD, ACTION_TYPE.TDELETE, ACTION_TYPE.EDIT],
  operateTools: [],
  dataSource: [],
  // fetchConfig: {
  //   query: {
  //     service: (
  //       params: GetListParamProp<{ version: string; hxtFormula: object }>
  //     ) => {
  //       const { start_page, size, ...rest } = params;
  //       params = {
  //         start_page: start_page ?? 1,
  //         size: 0,
  //         ...rest
  //       };
  //
  //       return getSpecificationList(params);
  //     },
  //     param: () => {
  //       return {
  //         ...formRef.value.getFormData()
  //       };
  //     }
  //   }
  // },
  vxeTableConfig: {
    pagerConfig: {
      enabled: false
    }
  }
});
const rowData = ref({});
const formulaId = ref(route.query.id as string);

const formRef = ref();
const tableRef = ref();

// endregion

// region 页面公共方法集合
function storageConfigureChange<T>(key: string, val: T): void {
  const storageConfigure = $storage.configure;
  storageConfigure[key] = val;
  // $storage.configure = storageConfigure;
}

async function getSpecificationListData() {
  const params = {
    start_page: 1,
    size: 0,
    ...formRef.value.getFormData()
  };
  const res = await getSpecificationList(params);
  gridOption.dataSource = res.data;
}

// endregion

// region 页面及组件事件集合
const toPrevPage = () => {
  // router.go(-1);
  //window.history.back();
  router.push({
    name: "CabinetFormulaDetail",
    query: {
      ...proxy.$route.query
    }
  });
};

const search = () => {
  // tableRef.value.refresh();
  getSpecificationListData();
};

const actionClick = ({
  key,
  row
}: {
  key: ACTION_TYPE;
  row: SpecificationProp;
}) => {
  activeType.value = key;
  switch (key) {
    case ACTION_TYPE.TADD:
      showPopup.value = true;
      nextTick(() => {
        formSpecRef.value.resetFields();
        dynamicValidateForm.domains = [
          {
            key: 1,
            autata_value: "",
            third_value: ""
          }
        ];
      });
      break;
    case ACTION_TYPE.EDIT:
      showPopup.value = true;
      dynamicValidateForm.id = row.id;
      dynamicValidateForm.name = row.name;
      if (!row.thirdRelationList) {
        const splitKey = row.attr.includes(",") ? "," : "|";
        dynamicValidateForm.domains = row.attr.split(splitKey).map(item => {
          return {
            autata_value: item,
            third_value: ""
          };
        });
      } else {
        dynamicValidateForm.domains = (row.thirdRelationList ?? []).map(v => ({
          autata_value: v.autata_value,
          third_value: v.third_value
        }));
      }
      break;
    case ACTION_TYPE.TDELETE:
      proxy.$auMessageBox
        .confirm(
          t("formula_detail.delete_specification_confirm"),
          t("notice.title"),
          {
            type: "error"
          }
        )
        .then(() => {
          const checkedNodes = tableRef.value.getCheckboxRecords();

          for (let i = 0; i < checkedNodes.length; i++) {
            checkedNodes[i].delete_status = 0;
          }
          if (checkedNodes.length > 0) {
            specificationDelete({ delList: JSON.stringify(checkedNodes) }).then(
              res => {
                // tableRef.value.refresh();
                if (res.code === 200) {
                  VxeUI.modal.message({
                    content: t("notice.operation_success"),
                    status: "success"
                  });
                  getSpecificationListData();
                }
              }
            );
          }
        })
        .catch(() => {});
      break;
    default:
      break;
  }
};

//保存选择
const saveFormulaSpecification = () => {
  const arr = tableRef.value.getCheckboxRecords();
  router.push({
    name: "CabinetFormulaDetail",
    query: {
      ...proxy.$route.query,
      specIds: JSON.stringify(arr.map(v => v.id))
    }
  });
};

//回显已选中的规格
const getSpecificationListForSelect = () => {
  const params = { formula_subid: route.query.formula_subid };
  getMaterialListForFormula(params).then(res => {
    // console.log(res.data.specification_list);
    //tableRef.value.setCheckboxRow([10143, 10134, 10135, 10136], true);
  });
};

// 设置已选中的行
const setSelectRow = (rows: Record<string, any>[], checked: boolean) => {
  const $table = tableRef.value;
  if ($table) {
    console.log($table.vxeGridRef, rows);
    nextTick(() => {
      $table.vxeGridRef.setCheckboxRow(rows, checked);
    });
  }
};

// getSpecificationListForSelect();

const handleConfirm = async () => {
  formSpecRef.value.validate().then(res => {
    let formData = dynamicValidateForm;
    formSpecData.name = formData.name;

    const attr = [];
    if (formData.domains.length > 0) {
      for (let i = 0; i < formData.domains.length; i++) {
        if (!formData.domains[i].autata_value) {
          ElMessage({
            message: t("formula_detail.please_input_autata_value", {
              index: i + 1
            }),
            type: "error"
          });
          return;
        }
        attr.push(formData.domains[i].autata_value);
      }
      formSpecData.attr = attr.join(",");

      formSpecData.third_detail = JSON.stringify(formData.domains);
    } else {
      ElMessage({
        message: t("formula_detail.please_input_least_value"),
        type: "error"
      });
    }

    let api = specificationAdd;
    if (activeType.value === ACTION_TYPE.TADD) {
      api = specificationAdd;
    } else if (activeType.value === ACTION_TYPE.EDIT) {
      api = specificationUpdate;
      formSpecData.id = formData.id;
    }
    api(formSpecData).then(res => {
      if (res.code === 200) {
        ElMessage({
          message: formSpecData.id
            ? t("formula_detail.edit_specification_success")
            : t("formula_detail.add_specification_success"),
          type: "success"
        });
        showPopup.value = false;
        // tableRef.value.refresh();
        //xGrid.value.commitProxy("query");
        getSpecificationListData();
      }
    });
  });
};

const removeDomain = (item: Partial<SpecificationSubProp>) => {
  const index = dynamicValidateForm.domains.indexOf(item);
  if (index !== -1) {
    dynamicValidateForm.domains.splice(index, 1);
  }
};

const addDomain = () => {
  dynamicValidateForm.domains.push({
    key: Date.now(),
    autata_value: "",
    third_value: ""
  });
};

// endregion

onMounted(async () => {
  await getSpecificationListData();
  if (isString(route.query.specIds)) {
    const specIds = JSON.parse(route.query.specIds);
    const tableData = tableRef.value.vxeGridRef.getData();
    console.log(tableData);
    const filteredData = tableData.filter(item => specIds.includes(item.id));
    setSelectRow(filteredData, true);
  }
});
</script>
<style scoped>
.input-with-label {
  display: flex;
  gap: 0; /* 控制label和input之间的间距 */
  align-items: center;
}

.label {
  min-width: 100px; /* 固定label宽度 */
  white-space: nowrap; /* 防止文字换行 */
}

.formStyle {
  padding-right: 0;
  padding-bottom: 0;
  padding-left: 20px;
  margin-bottom: 20px;
}

/* .formItemStyle {
  margin-left: 10px;
} */
</style>
